package com.bbx.taxi.client.Adapter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.bbx.androidapi.util.DensityUtil;
import com.bbx.api.sdk.model.comm.returns.line.Cities;
import com.bbx.api.sdk.model.comm.returns.line.To_Cities;
import com.bbx.api.sdk.model.passanger.Return.Coupon.CouponList;
import com.bbx.api.sdk.model.passanger.Return.Coupon.Coupons;
import com.bbx.api.sdk.model.passanger.Return.Coupon.Metadata.CarClass;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.DB.LineDB;
import com.bbx.taxi.client.DB.Util.DBcolumns;
import com.bbx.taxi.client.Util.CouponUtils;
import com.bbx.taxi.client.Util.DateFormat;
import com.bbx.taxi.client.Util.TextViewAdaption;
import com.bbx.taxi.client.widget.MyViewPager;
import com.bbx.taxi.client.widget.textView.RotateTextView;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 优惠劵
 */
public class CouponAdapter extends BaseAdapter {
	private List<Coupons> list;
	private Activity main;
	private boolean isItemClick = false;
	private LineDB db_line;// 线路数据库
	private int coupon_id;

	public CouponAdapter(Activity context, List<Coupons> list) {
		this.list = list;
		main = context;
		db_line = new LineDB();
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;

	}

	public void setCoupon_id(int coupon_id) {
		this.coupon_id = coupon_id;
	}

	public boolean getItemClick() {
		return isItemClick;
	}

	public void setItemClick(boolean isItemClick) {
		this.isItemClick = isItemClick;
	}
    
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder viewholder;
		if (convertView == null) {
			LayoutInflater inflater = LayoutInflater.from(main);
			convertView = (View) inflater.inflate(R.layout.listitem_coupon,
					null);
			viewholder = new ViewHolder();
			viewholder.layout_top = (LinearLayout) convertView
					.findViewById(R.id.layout_top);
			viewholder.tv_money = (TextView) convertView.findViewById(R.id.tv_money);
			viewholder.tv_unit = (TextView) convertView.findViewById(R.id.tv_unit);
			viewholder.type = (TextView) convertView.findViewById(R.id.type);
			viewholder.line = (TextView) convertView.findViewById(R.id.line);
			viewholder.tv_mark = (RotateTextView) convertView.findViewById(R.id.tv_mark);
			viewholder.tv_tag = (TextView) convertView.findViewById(R.id.tv_tag);
			viewholder.tv_coupon_type = (TextView) convertView.findViewById(R.id.tv_coupon_type);
			viewholder.car_name=(TextView) convertView.findViewById(R.id.car_name);
			viewholder.expire_time = (TextView) convertView
					.findViewById(R.id.expire_time);
			viewholder.tv_sum_low = (TextView) convertView
					.findViewById(R.id.tv_sum_low);
			viewholder.tv_time_limit=(TextView) convertView
					.findViewById(R.id.tv_time_limit);
			viewholder.tv_gifter=(TextView) convertView
					.findViewById(R.id.tv_gifter);
			viewholder.tv_give=(TextView) convertView
					.findViewById(R.id.tv_give);
			viewholder.tv_expired=(TextView)convertView.findViewById(R.id.tv_expired);
			convertView.setTag(viewholder);
		} else
			viewholder = (ViewHolder) convertView.getTag();
		
		int num = 0;
		
		if(coupon_id==list.get(position).getId()){
			viewholder.layout_top.setBackgroundDrawable(main.getResources().getDrawable(R.drawable.yhq_bg_down));
		}
		else{
			viewholder.layout_top.setBackgroundDrawable(main.getResources().getDrawable(R.drawable.shape_yhq_list));
		}
		viewholder.tv_money.setText(list.get(position).getSum()+"");
		TextViewAdaption.onAdaption(main,viewholder.tv_money,DensityUtil.dip2px(main, 70),DensityUtil.dip2px(main, 50));
		CouponUtils.setCouponType(main,viewholder.tv_coupon_type,viewholder.tv_money,viewholder.tv_unit,list.get(position).getType());

		
		//添加标记，
		String tag=list.get(position).getTag();
		if(tag!=null&&!tag.equals("")){
			viewholder.tv_tag.setText("["+tag+"]");
		}else{
			viewholder.tv_tag.setText("");
		}
		/*****************************1和2，类型跟线路***********************************/
		if (list.get(position).getMetadata() != null) {
			viewholder.type.setText((++num+"、")+getType(list.get(position).getMetadata()
					.getUsabletype(),list.get(position).getMetadata()
					.getBusinessType()));
			viewholder.line.setText((++num+"、")+list.get(position).getLine_CN());
			viewholder.line.setVisibility(View.VISIBLE);

		}else{
			viewholder.line.setVisibility(View.GONE);
		}
		/*****************************3.可用车型******************************************/
		if (list.get(position).getMetadata() != null&&list.get(position).getMetadata().getCarClass()!=null) {
			String car_name="";
			List<CarClass> list_car=list.get(position).getMetadata().getCarClass();
			if(!list_car.isEmpty()&&list_car.get(0).getName().contains("*")){
				car_name="所有车型";
			}else{
				for(int i=0;i<list_car.size();i++){
					car_name+=list_car.get(i).getName()+(i!=(list_car.size()-1)?"、":"");
				}
			}
			viewholder.car_name.setText((++num+"、可用车型：")+car_name);
			viewholder.car_name.setVisibility(View.VISIBLE);
		}else{
			viewholder.car_name.setVisibility(View.GONE);
		}
		/*****************************3.时间***********************************/
		long expire_time=0;
		try{expire_time=Long.parseLong(list.get(position).getExpire_time())*1000;}catch (Exception e){}
		// 没有过期
		if ((expire_time >= new Date()
				.getTime())
				|| Long.parseLong(list.get(position).getExpire_time()) == 0) {
			viewholder.tv_money.setTextColor(main.getResources().getColor(
					R.color.btn_nor));
			viewholder.tv_unit.setTextColor(main.getResources().getColor(
					R.color.btn_nor));
			getMark(viewholder.tv_mark, list.get(position).getMetadata().getPaymode(), false);
			viewholder.tv_give.setVisibility(View.VISIBLE);
			viewholder.tv_expired.setVisibility(View.VISIBLE);
			setNDayLater(viewholder,expire_time);
		} else {// 过期
			viewholder.tv_give.setVisibility(View.GONE);
			viewholder.tv_expired.setVisibility(View.GONE);
			getMark(viewholder.tv_mark,list.get(position).getMetadata().getPaymode(),true);
			viewholder.tv_money.setTextColor(main.getResources().getColor(
					R.color.dark_notes));
			viewholder.tv_unit.setTextColor(main.getResources().getColor(
					R.color.dark_notes));
		}
        if(Long.parseLong(list.get(position)
				.getExpire_time())==0){
        	viewholder.expire_time.setText((++num+"、")+main
    				.getString(R.string.line_expire_no));
        }else{
        	//有起始时间
        	if(Long.parseLong(list.get(position).getEnable_time())!=0){
        		viewholder.expire_time.setText((++num+"、")+main
        				.getString(R.string.line_expire_time)
        				+ DateFormat.getTime2(Long.parseLong(list.get(position).getEnable_time()))+" ~ "+
        				 DateFormat.getTime2(Long.parseLong(list.get(position).getExpire_time())));
        	}
        	//没有有起始时间
        	else{
        		viewholder.expire_time.setText((++num+"、")+main
        				.getString(R.string.line_expire_time)
        				+ DateFormat.getTime2(Long.parseLong(list.get(position)
        						.getExpire_time())));
        	}
        
        }
        /*****************************4最低限额***********************************/
		try{
		//添加最低限额
		String sum_low=list.get(position).getMetadata().getSum_low_limit();
		if(sum_low!=null&&!sum_low.equals("")&&Double.parseDouble(sum_low)>0){
			viewholder.tv_sum_low.setVisibility(View.VISIBLE);
			viewholder.tv_sum_low.setText((++num+"、")+String.format(main.getString(R.string.line_sum_low), sum_low));
		}else{
			viewholder.tv_sum_low.setVisibility(View.GONE);
		}
		}catch(Exception e){}
		// viewholder.type2.setText(getType2(list.get(position).getMetadata().getUsabletype()));
        
		 /*****************************4或者5时间限制***********************************/
		try{
		//添加时间限制
		 String use_limit=list.get(position).getUseLimit();
		 if(use_limit!=null&&!use_limit.equals("")){
				viewholder.tv_time_limit.setVisibility(View.VISIBLE);
				viewholder.tv_time_limit.setText((++num+"、")+String.format(main.getString(R.string.line_time_limit), use_limit));
		 }else{
				viewholder.tv_time_limit.setVisibility(View.GONE);
		 }

		}catch(Exception e){}
		/*****************************5或者6赠送记录***********************************/
		try{
			int state=list.get(position).getState();
			String gifter=list.get(position).getGifter();
			String gift_time=list.get(position).getGift_time();
			if(state==state_gift&&gifter!=null&&!gifter.equals("")&&gift_time!=null&&!gift_time.equals("")){
				viewholder.tv_gifter.setVisibility(View.VISIBLE);
				viewholder.tv_gifter.setText((++num+"、")+String.format(main.getString(R.string.coupon_gifter),DateFormat.getTime2(Long.parseLong(gift_time)),gifter));
			}else{
				viewholder.tv_gifter.setVisibility(View.GONE);
			}

		}catch (Exception e){}

		//处理状态
		getSate(list.get(position).getState(),viewholder);
		return convertView;

	}

	public class ViewHolder {
		TextView tv_money, type, line, car_name,expire_time, tv_unit,tv_tag,tv_coupon_type,tv_sum_low,tv_time_limit,tv_gifter,
				tv_give,tv_expired;
		RotateTextView tv_mark;
		public LinearLayout layout_top;
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				// main.startActivity(new Intent(main,
				// AddAddressActivity.class));
				break;
			}
		};
	};
	public static int[] int_type=new int[]{8,1,2,4};
	Integer [] int_business_type=new Integer[]{1/*单程*/,2/*半日租*/,4/*日租*/};
	String [] str_business_type=new String[]{"单程","半日租","日租"};
	/**
	 * 体验卷类型2
	 */
	public String getType(String order_type,String str_business) {
		int type;
		int business_type = -1;
		try {
			type = Integer.parseInt(order_type);
		} catch (Exception e) {
			return "";
		}
		try {
			business_type = Integer.parseInt(str_business);
		} catch (Exception e) {
		}
		if(type==-1){
			//判断包车的是日租还是半日租还是单程的，，要用除外
			String mark="";
			//日租类型不等于全部
			if(business_type!=-1){
				for(int j=0;j<int_business_type.length;j++){
					//判断没有的要小于等于0
					if((business_type&int_business_type[j])<=0){
						mark+=str_business_type[j]+"、";
					}
				}
				//判断最后一个字是否是“、”,是的话去除
				if(mark.endsWith("、")){
					try{mark=mark.substring(0, mark.length()-1);}catch(Exception e){}
				}
				if(!mark.equals("")){
					mark="(除了"+mark+")";
				}
			}
			return main.getString(R.string.line_type_all)+mark;
		}else{

			Integer [] str_type=new Integer[]{R.string.sn,R.string.pc,R.string.bc,R.string.kj};
			String line_type=""+main.getString(R.string.apply_to);
			for(int i=0;i<int_type.length;i++){
				if((type&int_type[i])>0){
					String mark="";
					//如果是包车，则要显示日租类型
					if(i==2){
						//全部
						if(business_type==-1){
							mark="";
						}else{
							for(int j=0;j<int_business_type.length;j++){
								if((business_type&int_business_type[j])>0){
									mark+=str_business_type[j]+"、";
								}
							}
						}
						//判断最后一个字是否是“、”,是的话去除
						if(mark.endsWith("、")){
							try{mark=mark.substring(0, mark.length()-1);}catch(Exception e){}
						}
						mark="("+mark+")";
					}
					line_type=line_type+main.getString(str_type[i])+(business_type!=-1?mark:"")+"、";
				}
			}	
			if((line_type.charAt(line_type.length()-1)+"").equals("、")){
				 line_type= line_type.substring(0,line_type.length()-1)+"";
			}
			return line_type;
		}
	}
	public void getMark(RotateTextView textview,String paymode,boolean isExpire){
		String str_mark = CouponUtils.getMark(main, paymode,true);
		if(str_mark!=null&&!str_mark.equals("")){
			textview.setVisibility(View.VISIBLE);
			textview.setText(str_mark);
			//过期
			if(isExpire){
				textview.setBackground(main.getResources().getColor(R.color.dark_notes));
			}else{
				textview.setBackground(main.getResources().getColor(R.color.blue));
			}
		}else{
			textview.setVisibility(View.GONE);
		}
	}
	//可赠送
	public final static int state_no_gift=1;
	//已赠送
	public final static int state_gift=3;
	public void getSate(int state,ViewHolder viewholder){
		viewholder.tv_mark.setVisibility(viewholder.tv_mark.getVisibility());
		viewholder.tv_money.setTextColor(viewholder.tv_money.getTextColors());
		viewholder.tv_unit.setTextColor(viewholder.tv_unit.getTextColors());
		switch(state){
			//可赠送
			case state_no_gift:
				if(viewholder.tv_give.getVisibility()==View.GONE)
				viewholder.tv_give.setVisibility(View.VISIBLE);
				if(viewholder.tv_expired.getVisibility()==View.GONE)
				viewholder.tv_expired.setVisibility(View.VISIBLE);
				break;
			//已赠送
			case state_gift:
				viewholder.tv_give.setVisibility(View.GONE);
				viewholder.tv_expired.setVisibility(View.GONE);
				viewholder.tv_mark.setVisibility(View.VISIBLE);
				viewholder.tv_mark.setText("已赠送");
				viewholder.tv_mark.setBackground(main.getResources().getColor(R.color.dark_notes));
				viewholder.tv_money.setTextColor(main.getResources().getColor(
						R.color.dark_notes));
				viewholder.tv_unit.setTextColor(main.getResources().getColor(
						R.color.dark_notes));
				break;
			default:
				viewholder.tv_give.setVisibility(View.GONE);
				viewholder.tv_expired.setVisibility(View.GONE);
				break;
		}
	}

	/**
	 * 设置几天N
	 * @param viewholder
	 * @param expire_time    过期时间，单位毫秒
	 */
	public void setNDayLater(ViewHolder viewholder,long expire_time){
		long currentTime= new Date().getTime();
		long diff=(expire_time-currentTime)/1000;
		int minute=60;
		int hour=minute*60;
		int day=hour*24;
		int month=day*30;
		int year=month*12;
		if(expire_time==0){
			viewholder.tv_expired.setText("永久有效");
		}else if(diff>year){
			viewholder.tv_expired.setText(String.format(main.getString(R.string.n_expired),(diff/year)+"年"));
		}else if(diff>month&&diff<year){
			viewholder.tv_expired.setText(String.format(main.getString(R.string.n_expired),(diff/month)+"月"));
		}else if(diff>day&&diff<month){
			viewholder.tv_expired.setText(String.format(main.getString(R.string.n_expired),(diff/day)+"天"));
		}else if(diff>hour&&diff<day){
			viewholder.tv_expired.setText(String.format(main.getString(R.string.n_expired),(diff/hour)+"小时"));
		}else if(diff>minute&&diff<hour){
			viewholder.tv_expired.setText(String.format(main.getString(R.string.n_expired),(diff/minute)+"小时"));
		}
	}
}
